<template>
  <div class="newProject-container">
    <v-form ref="form" class="px-2">
      <v-container class="pl-14 pr-6">
        <v-row class="align-center line" no-gutters>
          <v-col cols="2" class="label-wrap">
            <span>Company Name</span>
          </v-col>
          <v-col class="text-left" cols="7">
            <v-text-field
              v-model="formData.company.name"
              v-validate="'required'"
              name="Company Name"
              class="gray-input"
              dense
              hide-details
              label="Enter the company Name"
              required
              solo
            ></v-text-field>
            <span class="vee-validate-error">
              {{ errors.first("Company Name") }}
            </span>
          </v-col>
          <v-col class="flex-grow-0 ml-2">
            <v-icon> mdi-magnify </v-icon>
          </v-col>
          <v-col v-if="formData.company.code" class="flex-grow-0 ml-2">
            <span>({{ formData.company.code }})</span>
          </v-col>
        </v-row>
        <v-row class="align-center line" no-gutters>
          <v-col cols="2" class="label-wrap">
            <span>Contact Person</span>
          </v-col>
          <v-col class="text-left" cols="3">
            <v-text-field
              v-model="formData.contactPerson"
              v-validate="'required'"
              name="Contact Person"
              class="gray-input"
              dense
              hide-details
              label="Enter the person name"
              required
              solo
            ></v-text-field>
            <span class="vee-validate-error">
              {{ errors.first("Contact Person") }}
            </span>
          </v-col>
          <v-col class="flex-grow-0 ml-2">
            <v-icon @click="openSelectContact"> mdi-account-box </v-icon>
          </v-col>
        </v-row>
        <v-row class="align-center line" no-gutters>
          <v-col cols="2" class="label-wrap">
            <span>Tel</span>
          </v-col>
          <v-col class="text-left" cols="3">
            <v-text-field
              v-model="formData.tel"
              v-validate="'required|phone'"
              name="Tel"
              class="gray-input"
              dense
              hide-details
              label="Enter phone number"
              required
              solo
            ></v-text-field>
            <span class="vee-validate-error">
              {{ errors.first("Tel") }}
            </span>
          </v-col>
        </v-row>
        <v-row class="align-center line" no-gutters>
          <v-col cols="2" class="label-wrap">
            <span>Address</span>
          </v-col>
          <v-col class="text-left" cols="9">
            <v-text-field
              v-model="formData.address"
              v-validate="'required'"
              name="Address"
              class="gray-input"
              dense
              hide-details
              label="Enter Address"
              required
              solo
            ></v-text-field>
            <span class="vee-validate-error">
              {{ errors.first("Address") }}
            </span>
          </v-col>
        </v-row>
      </v-container>
      <v-expansion-panels
        class="panels"
        accordion
        focusable
        flat
        multiple
        v-model="panel"
      >
        <v-expansion-panel>
          <v-expansion-panel-header>Project Details</v-expansion-panel-header>
          <v-expansion-panel-content>
            <ProjectDetails
              ref="projectDetails"
              :info="formData"
            ></ProjectDetails>
          </v-expansion-panel-content>
        </v-expansion-panel>
        <v-expansion-panel>
          <v-expansion-panel-header>Project Partner</v-expansion-panel-header>
          <v-expansion-panel-content class="text-left">
            <ProjectPartner
              :items="formData.partnerList"
              @open="openSelectPartnerContractor"
            ></ProjectPartner>
          </v-expansion-panel-content>
        </v-expansion-panel>
        <v-expansion-panel>
          <v-expansion-panel-header disable-icon-rotate>
            User Right
            <template v-slot:actions>
              <v-icon color="error"> mdi-tune </v-icon>
            </template>
          </v-expansion-panel-header>
          <v-expansion-panel-content class="text-left">
            <UserRight
              :items="formData.userRight.commonUserRightList"
            ></UserRight>
            <!-- <ValidationProvider>
            </ValidationProvider> -->
          </v-expansion-panel-content>
        </v-expansion-panel>
      </v-expansion-panels>
    </v-form>
    <SelectDialog
      v-model="showSelectDialog"
      :loading="!selectItems.length"
      :title="selectDialogTitle"
      :headers="selectHeaders"
      :items="selectItems"
      @click="clickSelectDialogTr"
      @close="closeSelectDialog"
      width="904"
    ></SelectDialog>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import SelectDialog from "@/components/Project/SelectDialog/SelectDialog.vue";
import ProjectPartner from "./ProjectPartner.vue";
import UserRight from "./UserRight.vue";
import ProjectDetails from "./ProjectDetails.vue";
import VForm from "vuetify/src/components/VForm/index";
import { DataTableHeader } from "vuetify/types";
import { IProjectForm } from "@/components/Project/index";
import {
  IPartner,
  IContact,
  IMember,
  ISupplier,
} from "@/components/Project/index";
@Component({
  components: {
    SelectDialog,
    ProjectPartner,
    UserRight,
    ProjectDetails,
  },
})
export default class NewProject extends Vue {
  panel = [0, 1, 2];
  // Form Data
  formData: IProjectForm = {
    id: "",
    //basic info
    company: {
      id: "",
      name: "",
      code: "",
    },
    contactPerson: "",
    tel: "",
    address: "",
    // Project Details
    projectName: "",
    priority: "",
    projectType: "",
    projectDescription: "",
    projectLocation: "",
    serviceProvider: "",
    startDate: "",
    endDate: "",
    // Project Partner
    partnerList: [],
    // User Right
    userRight: {
      commonUserRightList: [],
      advancedUserRightList: [],
    },
  };

  resetForm() {
    this.formData.id = "";
    this.formData.partnerList = [];
    this.formData.company = {
      id: "",
      name: "",
      code: "",
    };
    this.formData.userRight = {
      commonUserRightList: [],
      advancedUserRightList: [],
    };
    type VFormInstance = InstanceType<typeof VForm>;
    const formRef = this.$refs.form as VFormInstance;
    formRef.reset();
  }

  setFormData(formData: object) {
    Object.assign(this.formData, formData);
  }

  async validateFormData() {
    const valid: boolean = await this.$validator.validate();
    const projectDetailsValid = await (
      this.$refs.projectDetails as ProjectDetails
    ).$validator.validate();

    if (
      valid &&
      projectDetailsValid &&
      this.formData.partnerList.length &&
      this.formData.userRight.advancedUserRightList.length &&
      this.formData.userRight.commonUserRightList.length
    ) {
      return this.getFormData();
    } else {
      return false;
    }
  }

  getFormData(): IProjectForm {
    return JSON.parse(JSON.stringify(this.formData));
  }
  // select
  selectDialogTitle = "Select Contact";
  showSelectDialog = false;
  selectHeaders: Array<DataTableHeader> | null = null;
  selectItems: Array<IContact> | Array<IMember> | Array<ISupplier> = [];
  // 1.SelectContact 2.SelectSupplier 3.SelectMember
  selectStep = -1;
  // contactPerson
  selectedContact: IContact | null = null;
  contactHeader = [
    {
      text: "User ID",
      value: "userID",
    },
    {
      text: "Name",
      value: "userName",
    },
    {
      text: "Tel",
      value: "tel",
    },
    {
      text: "Location",
      value: "location",
    },
  ];
  get contactPersonList(): Array<IContact> {
    return this.$store.state.ProjectsStore.contactPersonList;
  }
  switchToContact() {
    this.selectStep = 1;
    this.selectHeaders = this.contactHeader;
    this.selectItems = this.contactPersonList;
  }
  openSelectContact() {
    this.selectDialogTitle = "Select Contact";
    this.switchToContact();
    this.openSelectDialog();
  }
  // Supplier
  selectedSupplier: ISupplier | null = null;
  supplierHeaders = [
    {
      text: "Contact Code",
      value: "contactCode",
    },
    {
      text: "Name",
      value: "companyName",
    },
  ];
  supplierItems: Array<ISupplier> = [];
  getSupplierItems() {
    new Promise<Array<ISupplier>>((res) => {
      const supplierItems = [
        {
          contractor: "CON",
          contactCode: "CON-0001",
          companyName: "Sample Contractor A",
        },
        {
          contractor: "CON",
          contactCode: "CON-0002",
          companyName: "Sample Contractor ",
        },
      ];

      setTimeout(() => {
        res(supplierItems);
      }, 800);
    }).then((res) => {
      this.supplierItems = res;
      if (this.selectStep === 2) {
        this.switchToSupplier();
      }
    });
  }
  switchToSupplier() {
    this.selectDialogTitle = "Select Project Partner-Contractor";
    this.selectStep = 2;
    this.selectHeaders = this.supplierHeaders;
    this.selectItems = this.supplierItems;
  }
  // Member
  selectedPartner: IMember | null = null;
  memberHeader = [
    {
      text: "User ID",
      value: "userID",
    },
    {
      text: "Name",
      value: "memberName",
    },
    {
      text: "Tel",
      value: "tel",
    },
    {
      text: "Location",
      value: "location",
    },
  ];
  memberItems: Array<IMember> = [];
  getMemberItems() {
    new Promise<Array<IMember>>((res) => {
      const memberItems = [
        {
          userID: "Sasa",
          memberName: "Sasa Chan",
          tel: "9348 2389",
          location: "Office",
        },
        {
          userID: "Admin",
          memberName: "Admin ",
          tel: "9322 2388",
          location: "Office",
        },
      ];

      setTimeout(() => {
        res(memberItems);
      }, 900);
    }).then((res) => {
      this.memberItems = res;
    });
  }
  switchToMember() {
    this.selectDialogTitle = "Select Project Partner-Contractor";
    this.selectStep = 3;
    this.selectHeaders = this.memberHeader;
    this.selectItems = this.memberItems;
  }
  // Select Action
  openSelectPartnerContractor() {
    this.switchToSupplier();
    this.openSelectDialog();
  }
  openSelectDialog() {
    this.showSelectDialog = true;
  }
  closeSelectDialog() {
    if ([1, 2].includes(this.selectStep)) {
      this.showSelectDialog = false;
    } else if (this.selectStep === 3) {
      this.switchToSupplier();
    }
  }
  partner: IPartner = this.createInitPartner();
  createInitPartner(): IPartner {
    return {
      id: "",
      userID: "",
      memberName: "",
      tel: "",
      location: "",
      contractor: "",
      contactCode: "",
      companyName: "",
    };
  }
  clickSelectDialogTr(item: IContact | ISupplier | ISupplier) {
    if (this.selectStep === 1) {
      const selectedItem = item as IContact;
      this.formData.contactPerson = selectedItem.userName;
      this.closeSelectDialog();
    } else if ([2, 3].includes(this.selectStep)) {
      const selectedItem = item;
      Object.assign(this.partner, selectedItem);
      if (this.selectStep === 2) {
        this.switchToMember();
      } else {
        this.partner.id = String(new Date().getTime());
        this.formData.partnerList.push(this.partner);
        this.partner = this.createInitPartner();
        this.showSelectDialog = false;
      }
    }
  }

  created() {
    this.getSupplierItems();
    this.getMemberItems();
  }
}
</script>

<style lang="scss" scoped>
@import "./NewProject.scss";
</style>
